import { useEffect, useState, useMemo, useCallback } from "react";

import { Form, Input, Table, Button, Badge, message, Popconfirm } from "antd";
import { useForm } from "antd/es/form/Form";
import { ColumnsType } from "antd/es/table";

import { meetingRoomList, deleteMeetingRoom } from "../../api/meeting";

import "./meeting-room.css";

import { MeetRoomAddEdit } from "./MeetRoomAdd&Edit";

// 一些可以不写在函数式组件内的变量和方法
interface SearchMeetingRoom {
    name: string;
    capacity: string;
    equipment: string;
}

export interface MeetingRoomSearchResult {
    id: number;
    name: string;
    capacity: number;
    equipment: string;
    location: string;
    description: string;
    isBooked: boolean;
    createTime: Date;
    updateTime: Date;
}

export function MeetingRoom() {
    // hooks变量书写区
    const [form] = useForm();
    const [meetingRoomResult, setMeetingRoomResult] = useState<Array<MeetingRoomSearchResult>>([]);
    const [pageNo, setPageNo] = useState<number>(1);
    const [pageSize, setPageSize] = useState<number>(10);
    const [num, setNum] = useState<number>(0);
    const [isOpenModal, setIsOpenModal] = useState<boolean>(false);
    const [title, setTitle] = useState<string>("创建会议室");
    const [id, setId] = useState<number>();
    
    // 非hooks变量书写区
    const columns: ColumnsType<MeetingRoomSearchResult> = useMemo(()=>([
        {
            title: '名称',
            dataIndex: 'name'
        },
        {
            title: '容纳人数',
            dataIndex: 'capacity',
        },
        {
            title: '位置',
            dataIndex: 'location'
        },
        {
            title: '设备',
            dataIndex: 'equipment'
        },
        {
            title: '描述',
            dataIndex: 'description'
        },
        {
            title: '添加时间',
            dataIndex: 'createTime'
        },
        {
            title: '上次更新时间',
            dataIndex: 'updateTime'
        },
        {
            title: '预定状态',
            dataIndex: 'isBooked',
            render: (_, record) => (
                record.isBooked ? <Badge status="error">已被预订</Badge> : <Badge status="success">可预定</Badge>
            )
        },
        {
            title: '操作',
            render: (_, record) => (
                <div>
                    <Popconfirm
                        title="会议室删除"
                        description="确定删除吗？"
                        onConfirm={()=>handleDelete(record.id)}
                        okText="确定"
                        cancelText="取消">
                        <a href="#">删除</a>
                    </Popconfirm>
                    <br />
                    <a href="#" onClick={()=>{setIsOpenModal(true);setTitle("编辑会议室"); setId(record.id)}}>编辑</a>
                </div>
            )
        }
    ]), []);

    // 方法书写区
    const searchMeetingRoom = useCallback((values: SearchMeetingRoom)=>{
        const { name, capacity, equipment } = values;
        meetingRoomList(name, Number(capacity), equipment, pageNo, pageSize).then(res =>{
            if(res.status === 201 || res.status === 200) {
                setMeetingRoomResult(res.data.meetingRooms.map((item: MeetingRoomSearchResult) => ({ key: item.id, ...item })))
            }
        }, err=>{
            message.error("系统繁忙，请稍后重试");
        })
    }, []);
    const changePage = useCallback((pageNo: number, pageSize: number)=>{
        setPageNo(pageNo);
        setPageSize(pageSize);
    }, []);
    const handleDelete = useCallback((id: number)=>{
        deleteMeetingRoom(id).then(() => {
            message.success("删除成功");
            setNum(Math.random());
        }, err=> {
            console.error("错误日志====", err);
            message.error("删除失败");
        })
    }, []);

    // 生命周期书写区
    useEffect(()=>{
        searchMeetingRoom({
            name: form.getFieldValue("name"),
            capacity: form.getFieldValue("capacity"),
            equipment: form.getFieldValue("equipment"),
        })
    }, [pageNo, pageSize, num]); 

    // DOM结构书写区
    return (
        <div className="meeting-room">
            <div className="meeting-room__form">
                <Form
                    form={form}
                    onFinish={searchMeetingRoom}
                    name="search"
                    layout="inline"
                    colon={false}
                >
                    <Form.Item label="会议室名称" name="name">
                        <Input />
                    </Form.Item>

                    <Form.Item label="容纳人数" name="capacity">
                        <Input />
                    </Form.Item>

                    <Form.Item label="位置" name="location">
                        <Input />
                    </Form.Item>

                    <Form.Item label=" ">
                        <Button type="primary" htmlType="submit">
                            搜索会议室
                        </Button>
                        <Button type="primary" style={{background: 'green', marginLeft: '10px'}}
                            onClick={()=>{setIsOpenModal(true); setTitle("创建会议室")}}>
                            添加会议室
                        </Button>
                    </Form.Item>
                </Form>
            </div>
            <div className="meeting-room__table">
                <Table columns={columns} dataSource={meetingRoomResult} pagination={{
                    current: pageNo,
                    pageSize,
                    onChange: changePage
                }}></Table>
            </div>
            <MeetRoomAddEdit id={id} isOpen={isOpenModal} handleClose={()=>{setIsOpenModal(false); setNum(Math.random())}} title={title}></MeetRoomAddEdit>
        </div>
    )
}